package com.lf.web.html;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.log4j.Logger;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class MakeHtml {

    public static final Logger LOGGER = Logger.getLogger(MakeHtml.class);

    Configuration cf = null;
    ServletContext application = null;
    Template t = null;

    private String outfile = "";
    private Map data = null;
    private File templatefile = null;

    public MakeHtml() {

        cf = new Configuration();
    }

    public void setOutfile(String outfile) {
        this.outfile = outfile;
    }

    public void setData(Map data) {
        this.data = data;
    }

    public void setTemplatefile(String templatefile) {
        this.templatefile = new File(templatefile);
    }

    public boolean OutHtml() {
        boolean result = false;
        try {
            cf = new Configuration();
            cf.setDirectoryForTemplateLoading(templatefile.getParentFile());
            t = cf.getTemplate(templatefile.getName());
            t.setEncoding("UTF-8");

            File html = new File(outfile);
            if (!html.getParentFile().exists())
                html.getParentFile().mkdirs();
            Writer out = new OutputStreamWriter(new FileOutputStream(html), "UTF-8");
            t.process(data, out);
            out.flush();
            out.close();
            result = true;
        } catch (IOException e) {
            LOGGER.error("输出静态页面异常：" + e.getMessage());
        } catch (TemplateException e) {
            LOGGER.error("输出静态页面模板异常：" + e.getMessage());
        }
        return result;
    }

}
